package cn.fulong.smebj.admin.service.impl;

import cn.fulong.frame.config.Result;
import cn.fulong.frame.consts.Constant;
import cn.fulong.frame.utils.MD5Util;
import cn.fulong.frame.utils.RSACoder;
import cn.fulong.smebj.admin.service.LoginService;
import cn.fulong.smebj.entity.User;
import cn.fulong.smebj.mapper.UserMapper;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户名+密码登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public Result<Object> login(User user) {
        Map<String,Object> userJson = Maps.newHashMap();
        try {
            String sql = "select id, real_name,role_id from user where user_name=? and password=?";
            userJson = jdbcTemplate.queryForMap(sql,new Object[]{user.getUserName(),user.getPassword()});
            // 判断用户名密码
            if (userJson.isEmpty()) {
                return Result.failure("用户名或密码错误");
            }
            byte[] encodedData = RSACoder.encryptByPublicKey(userJson.get("id").toString(), Constant.RSA.PUBLIC_KEY);
            String token = RSACoder.encryptBASE64(encodedData);
            userJson.put("token", token);
        } catch (Exception e) {
            return Result.failure("用户名或密码错误");
        }
        return Result.success(userJson);
    }

    @Override
    public Result<Object> register(User user) {
        List<User> check = userMapper.checkIfExist(user.getUserName());
        if(check.size() > 0){
            return Result.failure("注册失败，用户名已存在");
        }
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        return Result.success("注册成功");
    }

    @Override
    public Result<Object> modifyPassword(String oldPassword, String newPassword, String userJson,String flag) {
        if(StringUtils.isBlank(newPassword)){
            return Result.failure("输入参数错误。");
        }
        // 从当前登录用户信息中获取id
        JSONObject user = JSONObject.parseObject(userJson);

        if(!MD5Util.getMD5(oldPassword).equals(user.get("password"))){
            return Result.failure("旧密码输入不正确。");
        }
        //修改密码
        jdbcTemplate.update("update sys_user set password=? where id=?",new Object[]{MD5Util.getMD5(newPassword),user.get("id")});
        return Result.success();
    }
}
